package com.small.nine.wxmp.config;

import cn.hutool.http.HttpUtil;
import com.small.nine.wxmp.common.constant.WxConstant;
import com.small.nine.wxmp.domain.bean.wx.WxMenuBean;
import com.small.nine.wxmp.domain.bean.wx.WxMenuButtonBean;
import com.small.nine.wxmp.service.WxService;
import com.small.nine.wxmp.utils.wx.JsonUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 微信菜单
 *
 * @author sheng_zs@126.com
 * @date 2021-08-05 14:55
 */
@Slf4j
@Data
@Configuration
@ConfigurationProperties("wx.menu")
public class WxMenuConfig {
    /**
     * 是否自动创建
     */
    private Boolean enable;
    /**
     * 菜单
     */
    private List<WxMenuButtonBean> buttons;

    @Resource
    private WxService wxService;

    /**
     * 创建菜单
     */
    @PostConstruct
    private void createMenu() {
        if (Objects.equals(enable, true)) {
            WxMenuBean menuBean = new WxMenuBean();
            menuBean.setButtons(buttons);
            // 创建菜单
            String body = JsonUtils.writeValueAsString(menuBean);
            String post = HttpUtil.post(String.format(WxConstant.URL_MENU_CREATE_POST, wxService.getAccessToken()), body);
            log.info("自动创建微信公众号菜单\n{}\n创建信息：{}", body, post);
            Map<String, Object> map = JsonUtils.readValueAsMap(post);
            Object errCode;
            if (Objects.isNull(map) || Objects.isNull(errCode = map.get("errcode")) || !Objects.equals(errCode, 0)) {
                throw new RuntimeException("自动创建微信公众号菜单错误：" + post);
            }
        }
    }
}
